#!/usr/bin/env python

import Modules.Pygmund.Ego as Ego
from sys import argv as args

__version__ = "1.0"
__copyright__ = "2010, G. John Schutte IV, SnohomaNET (www.snohoma.net)"
__doc__ = """\
Application Server Launcher
	WIKI: http://cognition-app-framework.googlecode.com
	Developer: SnohomaNET (www.snohoma.net)
	
Description:
	Ego Application Server Controller
	
Usage:
	$ ./cognition.py start|stop|restart|status|help
	
"""
help = __doc__

def isRunning():
	# Check if Cognition is running.
	import Modules.Pygmund.Id as Id
	from os.path import exists
	from Modules.Pygmund.Utilities import AddSep
	
	conf = Id.Init("id/cognition.conf")
	if not conf:
		return { "error" : "Could not load configuration file." }
	
	conf = conf.Get("EGO")
	status = {}
	status["host"] = conf["hostname"]
	status["port"] = str(conf["port"])
	status["type"] = conf["server-type"]
	
	if exists(AddSep(conf["pid-dir"]) + conf["pid-file"]):
		pid = open(AddSep(conf["pid-dir"]) + conf["pid-file"], "rb").read()
		if exists("/proc/" + pid):
			status["state"] = True
			status["pid"] = pid
		else:
			status["state"] = False
			status["pid"] = 0
	else:
		status["state"] = False
		status["pid"] = 0
	
	return status
	
def main(command="start"):
	if command == "start":
		# Start Ego Server...
		r = isRunning()
		if "error" in r:
			return (False, r["error"])
		else:
			if not r["state"]:
				Ego.Start("id/cognition.conf")
				return (True, "")
			else:
				return (False, "Server is already running.")
				
	elif command == "stop":
		# Stop the Ego Server...
		r = isRunning()
		if "error" in r:
			return (False, r["error"])
		else:
			if r["state"]:
				Ego.Stop("id/cognition.conf")
				return (True, "")
			else:
				return (False, "Server is not running.")
		
	elif command == "restart":
		# Restart the Ego Server...
		r = isRunning()
		if "error" in r:
			return (False, r["error"])
		else:
			if r["state"]:
				Ego.Restart("id/cognition.conf")
				return (True, "")
			else:
				return (False, "Server is not running.")
		
	elif command == "help":
		return (True, help)
	
	elif command == "status":
		# Print current status of the server, as well as host:port and type
		r = isRunning()
		if "error" in r:
			return (False, r["error"])
		else:
			if r["state"]:
				return (True, "Server is active and running in %(type)s mode!\n\thttp://%(host)s:%(port)s\n\tProcess ID: %(pid)s" % r)
			else:
				return (True, "Server is currently inactive.")
	else:
		# Return Error...
		return (False, "Invalid Command '%s'" % command)
	return (True, r)

if len(args) < 2:
	print help
else:
	r = main(args[1])
	if not r[0]:
		print "Error: " + r[1]
	else:
		print r[1]

